from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import time

# 使用配置文件管理用户名、密码、URL等
from config import USER_NAME, PASSWORD, LOGIN_URL


def wait_for_element(driver, xpath, timeout=10):
    """
    等待直到页面元素出现
    """
    wait = WebDriverWait(driver, timeout)
    return wait.until(EC.presence_of_element_located((By.XPATH, xpath)))


def login(driver, phone, password):
    """
    执行登录操作
    """
    phone_input = wait_for_element(driver, "//input[@placeholder='请输入手机号']")
    password_input = wait_for_element(driver, "//input[@placeholder='请输入密码']")
    login_button = wait_for_element(driver, "//button[contains(text(),'登录')]")

    phone_input.send_keys(phone)
    password_input.send_keys(password)
    login_button.click()


def navigate_and_check(driver, xpath, check_xpath=None):
    """
    导航到指定页面并检查特定元素
    """
    wait_for_element(driver, xpath).click()
    time.sleep(1)  # 等待页面反应
    if check_xpath:
        try:
            driver.find_element(By.XPATH, check_xpath)
            return True
        except:
            return False


def main():
    # 设置浏览器驱动路径
    edge_driver_path = "/path/to/your/msedgedriver"

    # 创建 Edge 服务对象
    edge_service = EdgeService(executable_path=edge_driver_path)

    # 创建 Edge 浏览器对象，传递服务对象
    driver = webdriver.Edge(service=edge_service)

    # 打开登录页面
    driver.get(LOGIN_URL)

    # 执行登录操作
    login(driver, USER_NAME, PASSWORD)

    # 导航至不同的页面并执行检查
    if navigate_and_check(driver, "XPATH_OF_LIST_BUTTON", "XPATH_OF_CHECK_ELEMENT"):
        print("列表页面加载成功")
    else:
        print("列表页面加载失败")

    # 其他导航和检查操作...

    # 关闭浏览器
    driver.quit()


if __name__ == "__main__":
    main()
